package net.dubboclub.http.netty.servlet;

import io.netty.handler.codec.http.CookieDecoder;
import io.netty.handler.codec.http.DefaultHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;

import javax.servlet.http.Cookie;
import java.util.HashSet;
import java.util.Set;

/**
 * @date: 2016/3/8.
 * @author:bieber.
 * @project:dubbo-side.
 * @package:com.alibaba.dubbo.remoting.http.netty.servlet.
 * @version:1.0.0
 * @fix:
 * @description: 描述功能
 */
public abstract class NettyHttpServlet {

    protected Cookie[] decodeCookies(DefaultHttpRequest request){
        if(!hasCookies(request)){
            return new Cookie[0];
        }
        HttpHeaders httpHeaders = request.headers();
        Set<io.netty.handler.codec.http.Cookie> cookieSet = CookieDecoder.decode(httpHeaders.get(HttpHeaders.Names.SET_COOKIE));
        Set<Cookie> servletCookies = new HashSet<Cookie>();
        for(io.netty.handler.codec.http.Cookie cookie:cookieSet){
            Cookie servletCookie = new Cookie(cookie.getName(),cookie.getValue());
            servletCookies.add(servletCookie);
            servletCookie.setComment(cookie.getComment());
            servletCookie.setDomain(cookie.getDomain());
            servletCookie.setHttpOnly(cookie.isHttpOnly());
            servletCookie.setMaxAge((int) cookie.getMaxAge());
            servletCookie.setPath(cookie.getPath());
            servletCookie.setSecure(cookie.isSecure());
            servletCookie.setVersion(cookie.getVersion());
        }
        return servletCookies.toArray(new Cookie[0]);
    }

    protected io.netty.handler.codec.http.Cookie[] encodeCookies(DefaultHttpRequest request){
        if(!hasCookies(request)){
            return new io.netty.handler.codec.http.Cookie[0];
        }
        Set<io.netty.handler.codec.http.Cookie> cookieSet = CookieDecoder.decode(request.headers().get(HttpHeaders.Names.SET_COOKIE));
        return cookieSet.toArray(new io.netty.handler.codec.http.Cookie[0]);
    }

    private boolean hasCookies(DefaultHttpRequest request){
        return request.headers().contains(HttpHeaders.Names.SET_COOKIE);
    }

    protected io.netty.handler.codec.http.Cookie encodeCookie(Cookie cookie){
        io.netty.handler.codec.http.Cookie nettyCookie = new io.netty.handler.codec.http.DefaultCookie(cookie.getName(),cookie.getValue());
        nettyCookie.setComment(cookie.getComment());
        nettyCookie.setDomain(cookie.getDomain());
        nettyCookie.setHttpOnly(cookie.isHttpOnly());
        nettyCookie.setMaxAge(cookie.getMaxAge());
        nettyCookie.setPath(cookie.getPath());
        nettyCookie.setSecure(cookie.getSecure());
        nettyCookie.setVersion(cookie.getVersion());
        return nettyCookie;
    }

    protected UnsupportedOperationException reject(){
        return  new UnsupportedOperationException();
    }
}
